<?php

namespace App\Http\Controllers;
use App\Models\Doctor;
use App\Models\Order;
use App\Util\Url;
use Easemob\Attachment;
use Easemob\Auth;
use Easemob\Group;
use Easemob\Message;
use Easemob\Push;
use Easemob\Room;
use Easemob\User;
use Easemob\UserMetadata;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\BaseController;
use Illuminate\Support\Facades\Redis;

class Easemob extends Controller
{
    /**
     * 初始化参数
     *
     * @param array $options
     * @param $options ['client_id']
     * @param $options ['client_secret']
     * @param $options ['org_name']
     * @param $options ['app_name']
     */
    public function __construct()
    {
        if (!empty (config('omnipay.Im.org_name')) && !empty (config('omnipay.Im.app_name'))) {
            $this->url = config('omnipay.Im.url') . config('omnipay.Im.org_name') . '/' . config('omnipay.Im.app_name') . '/';
        }
    }

    /**
     *获取token
     */
    public function getToken()
    {
        if(!empty(Redis::get("hx_access_token"))){
            return "Authorization:Bearer " . Redis::get("hx_access_token");
        }
        $options = array(
            "grant_type" => "client_credentials",
            "client_id" =>config('omnipay.Im.client_id'),
            "client_secret" => config('omnipay.Im.client_secret')
        );
        //json_encode()函数，可将PHP数组或对象转成json字符串，使用json_decode()函数，可以将json字符串转换为PHP数组或对象
        $body = json_encode($options);
        //使用 $GLOBALS 替代 global
        $url = $this->url . 'token';
        //$url=$base_url.'token';
        $tokenResult = $this->postCurl($url, $body, $header = array());
        if(isset($tokenResult['access_token']) && !empty($tokenResult['access_token'])){
             Redis::setex("hx_access_token", $tokenResult['expires_in'] - 60, $tokenResult['access_token']);
        }
//        return $tokenResult['access_token'];
        return "Authorization:Bearer " . $tokenResult['access_token'];
    }

    //同步推送
    public function sendSyncPush($filter)
    {
        $url = $this->url . 'push/sync/'.$filter['user'];
        $options = array(
            "strategy" => 3,
            "pushMessage" => array(
                "title" => $filter['title'],
                "content" =>  $filter['content'],
                "sub_title" => $filter['sub_title'],
            )
        );
        $body = json_encode($options);
        $header = array($this->getToken());
        $result = $this->postCurl($url, $body, $header,"POST");
        return $result;
    }

    /**
     * @param $filter
     * @return mixed
     * 异步推送
     */
    public function sendSinglePush($filter)
    {
        $url = $this->url . 'push/single';
        $options = array(
            "targets" => $filter['user'],
            "pushMessage" => array(
                "title" => $filter['title'],
                "content" =>  $filter['content'],
                "sub_title" => $filter['sub_title'],
            ),
        );
        $body = json_encode($options);
        $header = array($this->getToken());
        $result = $this->postCurl($url, $body, $header,"POST");
        return $result;
    }




    /**
     * 授权注册
     */                     //123456
    //gt123456
    public function createUser($username, $password)
    {
        $url = $this->url . 'users';
        $options = array(
            "username" => $username,
            "password" => $password
        );
        $body = json_encode($options);
        $header = array($this->getToken());
        $result = $this->postCurl($url, $body, $header);
        return $result;
    }

    /*
    批量注册用户
    */
    public function createUsers($options)
    {
        $url = $this->url . 'users';
        $body = json_encode($options);
        $header = array($this->getToken());
        $result = $this->postCurl($url, $body, $header);
        return $result;
    }

    /*
    重置用户密码
    */
    public function resetPassword($username, $newpassword)
    {
        $url = $this->url . 'users/' . $username . '/password';
        $options = array(
            "newpassword" => $newpassword
        );
        $body = json_encode($options);
        $header = array($this->getToken());
        $result = $this->postCurl($url, $body, $header, "PUT");
        return $result;
    }

    /*
            修改用户昵称
        */
    public function editNickname($username, $nickname)
    {
        $url = $this->url . 'users/' . $username;
        $options = array(
            "nickname" => $nickname
        );
        $body = json_encode($options);
        $header = array($this->getToken());
        $result = $this->postCurl($url, $body, $header, 'PUT');
        return $result;
    }

    /*
    获取单个用户
    */
    public function getUser($username)
    {
        $url = $this->url . 'users/' . $username;
        $header = array($this->getToken());
        $result = $this->postCurl($url, '', $header, "GET");
        return $result;
    }

    /*
    删除单个用户
    */
    public function deleteUser($username)
    {
        $url = $this->url . 'users/' . $username;
        $header = array($this->getToken());
        $result = $this->postCurl($url, '', $header, 'DELETE');
        return $result;
    }

    /*
    删除批量用户
    limit:建议在100-500之间，、
    注：具体删除哪些并没有指定, 可以在返回值中查看。
    */
    function deleteUsers($limit)
    {
        $url = $this->url . 'users?limit=' . $limit;
        $header = array($this->getToken());
        $result = $this->postCurl($url, '', $header, 'DELETE');
        return $result;

    }

    /*
    查看用户是否在线
    */
    public function isOnline($username)
    {
        $url = $this->url . 'users/' . $username . '/status';
        $header = array($this->getToken());
        $result = $this->postCurl($url, '', $header, 'GET');
        return $result;
    }

    /*
    查看用户离线消息数
    */
    public function getOfflineMessages($username)
    {
        $url = $this->url . 'users/' . $username . '/offline_msg_count';
        $header = array($this->getToken());
        $result = $this->postCurl($url, '', $header, 'GET');
        return $result;

    }

    /*
    查看某条消息的离线状态
    ----deliverd 表示此用户的该条离线消息已经收到
    */
    public function getOfflineMessageStatus($username, $msg_id)
    {
        $url = $this->url . 'users/' . $username . '/offline_msg_status/' . $msg_id;
        $header = array($this->getToken());
        $result = $this->postCurl($url, '', $header, 'GET');
        return $result;

    }

    /*
     *禁用用户账号
     */
    public function deactiveUser($username)
    {
        $url = $this->url . 'users/' . $username . '/deactivate';
        $header = array($this->getToken());
        $result = $this->postCurl($url, '', $header);
        return $result;
    }

    /*
    解禁用户账号
    */
    public function activeUser($username)
    {
        $url = $this->url . 'users/' . $username . '/activate';
        $header = array($this->getToken());
        $result = $this->postCurl($url, '', $header);
        return $result;
    }

    /*
    强制用户下线
    */
    public function disconnectUser($username)
    {
        $url = $this->url . 'users/' . $username . '/disconnect';
        $header = array($this->getToken());
        $result = $this->postCurl($url, '', $header, 'GET');
        return $result;
    }

//--------------------------------------------------------发送消息

    /**
     *    管理员给群发消息
     * */
    public function sendGroupText($from = "admin", $group_id, $mes)
    {
        $url = $this->url . 'messages/chatgroups';
        $data = [
            'from' => $from,
            'to' => [$group_id],
            'type' => 'txt',
            'need_group_ack' => false,
            'body' => [
                'msg' => $mes
            ],
            'ext' => [
                'em_ignore_notification' => true, "ext1" => "你好呀!"
            ]
        ];
        $b = json_encode($data);
        $header = array($this->getToken());
        $result = $this->postCurl($url, $b, $header);
        return $result;
    }




    /*
    发送文本消息
    */
    public function sendText($from = "admin", $target_type, $target, $content, $ext)
    {
        $url = $this->url . 'messages';
        $body['target_type'] = $target_type;
        $body['target'] = $target;
        $options['type'] = "txt";
        $options['msg'] = $content;
        $body['msg'] = $options;
        $body['action'] = 'senddiv';
        $body['from'] = $from;
        $body['ext'] = $ext;
        $b = json_encode($body);
        $header = array($this->getToken());
        $result = $this->postCurl($url, $b, $header);
//        $result=$this->postCurl($url,$body,$header);
        //dump($result);
        return $result;
    }

    /**
     * @param $filter
     * @throws \Exception
     * 发送图文消息通过sdk
     */
    public function isUsersOnline()
    {
        // 初始化授权对象，环信 token 初始化
        $easemob = config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        // 实例化对象
        $user = new User($auth);
        $doc = new Doctor();
        $doctor = $doc->where([['state','=',1]])->pluck("id");
        $arr = [];
        foreach ($doctor as $k => $v) {
            $arr[] = 'doctor' . config("omnipay.Im.salt") . $v;
        }
        $success = $user->isUsersOnline($arr);
        $docs = [];
        foreach ($success as $k => $v) {
            $doc_id = substr($k, 12);
            if ($v === true) {
                $doc->where([['id', '=', $doc_id]])->update(['online' => 1]);
                $docs[] = $doc_id;
            } else {
                $doc->where([['id', '=', $doc_id]])->update(['online' => 0]);
            }
        }
       return $docs;//"success";
    }
   /**
     * @param $filter
     * @throws \Exception
     * 发送图文消息通过sdk
     */
    public function sendTextBySdk($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob =config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        // 实例化对象
        $message = new Message($auth);
        // 发送文本消息（仅发送给在线用户，消息同步给发送发）
        $msg = array(
            'msg' => $filter['text'],
            // 扩展，可以没有这个字段，但是如果有，值不能是 “ext:null” 这种形式，否则出错。
            'ext' => array(
                'ext1' => 'val1',
                'ext2' => 'val2',
            ),
        );
        if (is_array($filter['username'])) {
            $user = $filter['username'];
        } else {
            $user = array($filter['username']);
        }
        if (isset($filter['send_user'])) {
            $send_user = $filter['send_user'];
        } else {
            $send_user = "admin";
        }
        $success = $message->text('users', $user, $msg, $send_user, true);
        if ($success){
            return $success;
        }
        return "发送失败!";
    }


    /**
     * @param $filter
     * @throws \Exception
     * 发送图文消息通过sdk
     */
    public function sendImageBySdk($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob =config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        // 实例化对象
        $message = new Message($auth);
        // 发送图片消息
        $msg = array(
            'filename' =>isset($filter['file_name'])?$filter['file_name']:"",   // 图片名称
            'uuid' =>isset($filter['file_uuid'])?$filter['file_uuid']:"",//'a4364f90-b0d8-11ec-8cfe-b57d5aca4e63',   // 成功上传文件返回的UUID
            'secret' =>isset($filter['secret'])?$filter['secret']:"",// 'pDZPmrDYEeyGTyPdhVc_kj_MzWvSzIfi3bg_fgkvpVjvQAo5', // 成功上传文件后返回的secret
            'size' => array(    // 图片尺寸；height：高度，width：宽
                'width' => 36,
                'height' => 36,
            )
        );
        if(is_array($filter['username'])){
            $user = $filter['username'];
        }else{
            $user = array($filter['username']);
        }
        $success = $message->image('users',$user, $msg, 'admin');
        if ($success){
            return $success;
        }
        return "发送失败!";
    }


    /**
     * @param $filter
     * @throws \Exception
     * 发送语音消息通过sdk
     */
    public function sendAudioBySdk($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob =config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        // 实例化对象
        $message = new Message($auth);
        // 发送语音消息
        $msg = array(
            'filename' =>isset($filter['file_name'])?$filter['file_name']:"",   // 图片名称
            'uuid' =>isset($filter['file_uuid'])?$filter['file_uuid']:"",//'a4364f90-b0d8-11ec-8cfe-b57d5aca4e63',   // 成功上传文件返回的UUID
            'secret' =>isset($filter['secret'])?$filter['secret']:"",// 'pDZPmrDYEeyGTyPdhVc_kj_MzWvSzIfi3bg_fgkvpVjvQAo5', // 成功上传文件后返回的secret
            'size' => array(    // 图片尺寸；height：高度，width：宽
                'width' => 36,
                'height' => 36,
            )
        );
        if(is_array($filter['username'])){
            $user = $filter['username'];
        }else{
            $user = array($filter['username']);
        }
        $success = $message->audio('users',$user, $msg, 'admin');
        if ($success){
            return $success;
        }
        return "发送失败!";
    }


    /**
     * @param $filter
     * @throws \Exception
     * 发送视频消息通过sdk
     */
    public function sendVideoBySdk($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob =config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        // 实例化对象
        $message = new Message($auth);
        // 发送语音消息
        $msg = array(
            'filename' =>isset($filter['file_name'])?$filter['file_name']:"",   // 图片名称
            'uuid' =>isset($filter['file_uuid'])?$filter['file_uuid']:"",//'a4364f90-b0d8-11ec-8cfe-b57d5aca4e63',   // 成功上传文件返回的UUID
            'secret' =>isset($filter['secret'])?$filter['secret']:"",// 'pDZPmrDYEeyGTyPdhVc_kj_MzWvSzIfi3bg_fgkvpVjvQAo5', // 成功上传文件后返回的secret
            'thumb_uuid' => isset($filter['file_uuid'])?$filter['file_uuid']:"",  // 成功上传视频缩略图返回的 UUID
            'thumb_secret' => isset($filter['secret'])?$filter['secret']:"",   // 成功上传视频缩略图后返回的secret
        );
        if(is_array($filter['username'])){
            $user = $filter['username'];
        }else{
            $user = array($filter['username']);
        }
        $success = $message->video('users',$user, $msg, 'admin');
        if ($success){
            return $success;
        }
        return "发送失败!";
    }



    /**
     * @param $filter
     * @throws \Exception
     * 发送语音消息通过sdk
     */
    public function sendFileBySdk($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob =config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        // 实例化对象
        $message = new Message($auth);
        // 发送语音消息
        $msg = array(
            'filename' =>isset($filter['file_name'])?$filter['file_name']:"",   // 图片名称
            'uuid' =>isset($filter['file_uuid'])?$filter['file_uuid']:"",//'a4364f90-b0d8-11ec-8cfe-b57d5aca4e63',   // 成功上传文件返回的UUID
            'secret' =>isset($filter['secret'])?$filter['secret']:"",// 'pDZPmrDYEeyGTyPdhVc_kj_MzWvSzIfi3bg_fgkvpVjvQAo5', // 成功上传文件后返回的secret
            'size' => array(    // 图片尺寸；height：高度，width：宽
                'width' => 36,
                'height' => 36,
            )
        );
        $user = array($filter['username']);
        $success = $message->file('users',$user, $msg, 'admin');
        if ($success){
            return $success;
        }
        return "发送失败!";
    }

    /**
     * @param $filter
     * @throws \Exception
     * 获取历史消息
     */
    public function getHistoryAsUri($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob =config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        // 实例化对象
        $message = new Message($auth);
        $time =  date("YmdH",strtotime($filter['time']));
        $success = $message->getHistoryAsUri($time);
        $base_path =  substr(__DIR__,0,-20).'public\upload/hxchat_'.$time.'.gz';
        $message->getHistoryAsLocalFile($time, $base_path);
        if ($success){
            return $success;
        }
        return "发送失败!";
    }




    /***
     * @param $filter
     * 上传文件
     */
    public function uploadFileBySdk($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob =config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        // 实例化对象
        $attachment = new Attachment($auth);
        $base_path =  substr(__DIR__,0,-20).'public/upload/';
        $file =$base_path.$filter['file'];
        $success = $attachment->uploadFile($file,true);
        if ($success){
            return $success;
        }
        return "上传失败!";
    }

    /***
     * @param $url
     * @param $body
     * @param $header
     * @param string $type
     * @return mixed
     *     创建群组
     */

    public function makeChatRoom($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob = config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        $admin = $filter['admin'];
        $private_group_name = $filter['group_name'];
        $private_group_desc = $filter['private_group_desc'];
        $users = array($filter['user']);
        $group = new Group($auth);
        $res = $group->createPrivateGroup($admin, $private_group_name, $private_group_desc, $users, 2, true);
        if ($res) {
            (new Order())->where([['id', '=', $filter['order_id']]])->update(['chatgroup_id' => $res]);
            return 'success';
        }
        return false;
    }

    /***
     * @param $filter
     * @return bool
     * @throws \Exception
     * 修改群公告
     */
    public function updateGroupAnnouncement($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob = config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        $group_id = (new Order())->where([['id', '=', $filter['order_id']]])->value("chatgroup_id");
        $group = new Group($auth);
        $res = $group->updateGroupAnnouncement($group_id,$filter['mes']);
        if ($res) {
            return true;
        }
    }



    /***
     * 强制下线
     */
    public function outLogin($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob = config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        $user = new User($auth);
        $res = $user->forceLogoutAllDevices($filter['username']);
        if ($res) {
            return true;
        }
    }


    /***
     * @param $filter
     * @return bool
     * @throws \Exception
     * 修改用户信息
     */
    public static function updateUserInfo($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob = config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        $metadata = new UserMetadata($auth);
        if (!empty($filter['image'])) {
            $lt['avatar'] = Url::getHttpHost() . '/upload/' . $filter['image'];
        }
        if (!empty($filter['name'])) {
            $lt['nickname'] = $filter['name'];
        }
        if (empty($lt)) {
            return false;
        }
        $res = $metadata->setMetadataToUser($filter['im_id'], $lt);
        if ($res) {
            return true;
        }
    }

    /**
     * @param $filter
     * @return bool
     * @throws \Exception
     * 获取用户属性
     */
    public static function getImUserInfo($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob = config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        $metadata = new UserMetadata($auth);
        $res = $metadata->getMetadataFromUser($filter['im_id']);
        dd($res);
        if ($res) {
            return true;
        }
    }








    /***
     * @param $filter
     * @return bool
     * @throws \Exception
     * 解散群聊
     */
    public function dissolveChatRoom($filter)
    {
        // 初始化授权对象，环信 token 初始化
        $easemob = config('omnipay.Im');
        $auth = new Auth($easemob['app_key'], $easemob['client_id'], $easemob['client_secret']);
        // 设置 REST 域名，沙箱环境使用，不是沙箱环境会自动获取
        if (isset($easemob['api_uri']) && $easemob['api_uri']) {
            $auth->setApiUri($easemob['api_uri']);
        }
        $group_id = (new Order())->where([['id', '=', $filter['order_id']]])->value("chatgroup_id");
        $group = new Group($auth);
        $res = $group->destroyGroup($group_id);
        if ($res) {
            return true;
        }
    }


    public function postCurl($url, $body, $header, $type = "POST")
    {
        //1.创建一个curl资源
        $ch = curl_init();
        //2.设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, $url);//设置url
        //1)设置请求头
        //array_push($header, 'Accept:application/json');
        array_push($header,'Content-Type:application/json');
        //array_push($header, 'http:multipart/form-data');
        //设置为false,只会获得响应的正文(true的话会连响应头一并获取到)
        curl_setopt($ch, CURLOPT_HEADER, 0);
//		curl_setopt ( $ch, CURLOPT_TIMEOUT,5); // 设置超时限制防止死循环
        //设置发起连接前的等待时间，如果设置为0，则无限等待。
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //2)设备请求体
        if (strlen($body) > 0) {
            //$b=json_encode($body,true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);//全部数据使用HTTP协议中的"POST"操作来发送。
        }
        //设置请求头
        if (count($header) > 0) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        //上传文件相关设置
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);// 从证书中检查SSL加密算

        //3)设置提交方式
        switch ($type) {
            case "GET":
                curl_setopt($ch, CURLOPT_HTTPGET, true);
                break;
            case "POST":
                curl_setopt($ch, CURLOPT_POST, true);
                break;
            case "PUT"://使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请求。这对于执行"DELETE" 或者其他更隐蔽的HTT
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                break;
            case "DELETE":
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
        }


        //4)在HTTP请求中包含一个"User-Agent: "头的字符串。-----必设

//		curl_setopt($ch, CURLOPT_USERAGENT, 'SSTS Browser/1.0');
//		curl_setopt($ch, CURLOPT_ENCODING, 'gzip');

        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)'); // 模拟用户使用的浏览器
        //5)


        //3.抓取URL并把它传递给浏览器
        $res = curl_exec($ch);

        $result = json_decode($res, true);
        //4.关闭curl资源，并且释放系统资源
        curl_close($ch);

        if (empty($result))

            return $res;
        else
            return $result;

    }

}
